'use client';

import { useState, useEffect } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { fetchDatasets } from '@/lib/api';

export default function DatasetPage() {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedDataset, setSelectedDataset] = useState(null);
  const [selectedTask, setSelectedTask] = useState(null);
  const searchParams = useSearchParams();
  const router = useRouter();
  const clinicalscene = searchParams.get('clinicalscene');


  // 动态获取数据集描述
  const [datasets, setDatasets] = useState([]);

  useEffect(() => {
    async function loadDatasets() {
      const response = await fetchDatasets();
      if (Array.isArray(response)) {
        const processed = response.map((item, idx) => ({
          id: item.name,
          name: item.name,
          type: item.type,
          image_count: item.image_count,
          medical_image_count: item.medical_image_count,
          description: item.type === '2d'
            ? `包含 ${item.image_count} 张2D医学影像`
            : `包含 ${item.medical_image_count} 个3D医学影像序列`,
          // path 不暴露
        }));
        setDatasets(processed);
      }
    }
    loadDatasets();
  }, []);

  // 根据临床场景动态生成任务列表
  const getTasksForClinicalScene = (scene) => {
    const taskConfig = {
      'lung-nodule': [
        {
          id: 'detection',
          name: '肺结节检测',
          description: '自动检测CT影像中的肺结节区域',
          icon: '🔍'
        },
        {
          id: 'segmentation',
          name: '肺结节分割',
          description: '精确分割肺结节区域边界',
          icon: '✂️'
        },
        {
          id: 'classification',
          name: '肺结节良恶性分类',
          description: '对检测到的肺结节进行良恶性分类诊断',
          icon: '📊'
        }
      ],
      'pneumonia': [
        {
          id: 'classification',
          name: '肺炎病原体分类',
          description: '对肺炎病灶进行病原体识、重症风险分层',
          icon: '📊'
        },
        // {
        //   id: 'regression',
        //   name: '耐药性预测',
        //   description: '对肺炎患者的耐药性进行预测',
        //   icon: '📊'
        // }
      ],
      'copd': [
        {
          "id": "segmentation",
          "name": "气道分割",
          "description": "分割CT影像中的气道区域",
          "icon": "🔍"
        },
        {
          "id": "classification",
          "name": "肺气肿分类",
          "description": "对肺气肿进行类别划分",
          "icon": "✂️"
        },
        {
          "id": "grading",
          "name": "肺气肿严重程度分级",
          "description": "对肺气肿严重程度分级",
          "icon": "📊"
        }
      ],
      'liver-cancer': [
        {
          id: 'segmentation',
          name: '肝癌区域分割',
          description: '精确分割肝癌病灶区域边界',
          icon: '✂️'
        },
        {
          id: 'classification',
          name: '肝癌分型',
          description: '对肝癌进行分型',
          icon: '📊'
        },
        {
          id: 'staging',
          name: '肝癌分期',
          description: '对肝癌进行分期诊断',
          icon: '📊'
        }
      ],
      'fatty-liver': [
        // {
        //   id: 'segmentation',
        //   name: '脂肪肝区域分割',
        //   description: '精确分割脂肪肝病灶区域边界',
        //   icon: '✂️'
        // },
        {
          id: 'classification',
          name: '脂肪肝分期诊断',
          description: '对脂肪肝进行分期诊断',
          icon: '📊'
        }
      ]
    };
    
    // 默认任务配置（通用）
    const defaultTasks = [
      {
        id: 'detection',
        name: '病灶检测',
        description: '自动检测医学影像中的异常区域',
        icon: '🔍'
      },
      {
        id: 'classification',
        name: '病灶分类',
        description: '对检测到的病灶进行分类诊断',
        icon: '📊'
      },
      {
        id: 'segmentation',
        name: '病灶分割',
        description: '精确分割病灶区域边界',
        icon: '✂️'
      }
    ];
    
    return taskConfig[scene] || defaultTasks;
  };

  const tasks = getTasksForClinicalScene(clinicalscene);

  const filteredDatasets = datasets.filter(dataset =>
    dataset.name.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const handleDatasetSelect = (dataset) => {
    // 更新选中的数据集状态，将用户点击的数据集对象保存起来
    setSelectedDataset(dataset);
  };

  const handleTaskSelect = (task) => {
    // 更新选中的任务状态，将用户点击的任务对象保存起来
    setSelectedTask(task);
  };

  const handleConfirm = () => {
    if (selectedDataset && selectedTask) {
      // 当数据集和任务都已选择时，进行页面跳转
      // 构建目标URL：/operation/{数据集ID}/{任务ID}?task={任务类型}
      // 这里的 selectedDataset.id 实际上是数据集名称（如 'chest-xray'）
      // 由于在 loadDatasets() 中将 item.name 赋值给了 id
      router.push(`/operation/${selectedDataset.id}/${selectedTask.id}?clinicalscene=${clinicalscene}`);
    }
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="container mx-auto px-4 py-8">
        <header className="mb-8">
          <nav className="text-sm text-gray-600 mb-4">
            <Link href="/" className="hover:text-blue-600">首页</Link> {' > '} 数据集与任务选择
          </nav>
          <h1 className="text-2xl font-bold text-gray-900">选择数据集与任务</h1>
        </header>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          {/* 数据集选择区域 */}
          <div>
            <h2 className="text-xl font-semibold mb-4">数据集查询与选择</h2>

            {/* 搜索框 */}
            <div className="mb-4">
              <input
                type="text"
                placeholder="搜索数据集..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>

            {/* 数据集列表 */}
            <div className="space-y-3 max-h-96 overflow-y-auto">
              {filteredDatasets.map((dataset) => (
                <div
                  key={dataset.id}
                  onClick={() => handleDatasetSelect(dataset)}
                  className={`p-4 border rounded-lg cursor-pointer transition-colors ${selectedDataset?.id === dataset.id
                    ? 'border-blue-500 bg-blue-50'
                    : 'border-gray-200 hover:border-gray-300'
                    }`}
                >
                  <h3 className="font-medium text-gray-900">{dataset.name}</h3>
                  <p className="text-sm text-gray-600 mt-1">{dataset.description}</p>
                  {/* <p className="text-sm text-gray-500 mt-1">数据量: {dataset.count} 张</p> */}
                </div>
              ))}
            </div>
          </div>

          {/* 临床应用场景选择 */}
          <div>
            <h2 className="text-xl font-semibold mb-4">临床应用场景选择</h2>
            <div className="space-y-4">
              {tasks.map((task) => (
                <div
                  key={task.id}
                  onClick={() => handleTaskSelect(task)}
                  className={`p-4 border-2 rounded-lg cursor-pointer transition-all ${selectedTask?.id === task.id
                    ? 'border-blue-500 bg-blue-50 shadow-md'
                    : 'border-gray-200 hover:border-gray-300 hover:shadow-sm'
                    }`}
                >
                  <div className="flex items-center">
                    <span className="text-2xl mr-3">{task.icon}</span>
                    <div>
                      <h3 className="font-medium text-gray-900">{task.name}</h3>
                      <p className="text-sm text-gray-600 mt-1">{task.description}</p>
                    </div>
                  </div>
                </div>
              ))}
            </div>

            {/* 选择状态显示 */}
            <div className="mt-6 p-4 bg-gray-50 rounded-lg">
              <h3 className="font-medium text-gray-900 mb-2">当前选择：</h3>
              <div className="space-y-2 text-sm">
                <div>
                  <span className="text-gray-600">数据集：</span>
                  <span className={selectedDataset ? 'text-blue-600 font-medium' : 'text-gray-400'}>
                    {selectedDataset ? selectedDataset.name : '未选择'}
                  </span>
                </div>
                <div>
                  <span className="text-gray-600">类型：</span>
                  <span className={selectedDataset ? 'text-blue-600 font-medium' : 'text-gray-400'}>
                    {selectedDataset ? (selectedDataset.type === '2d' ? '2D医学影像' : '3D医学影像') : '未选择'}
                  </span>
                </div>
                <div>
                  <span className="text-gray-600">任务：</span>
                  <span className={selectedTask ? 'text-blue-600 font-medium' : 'text-gray-400'}>
                    {selectedTask ? selectedTask.name : '未选择'}
                  </span>
                </div>
              </div>
            </div>

            {/* 确认按钮 */}
            <div className="mt-6">
              <button
                onClick={handleConfirm}
                disabled={!selectedDataset || !selectedTask}
                className={`w-full py-3 px-4 rounded-lg font-medium ${selectedDataset && selectedTask
                  ? 'bg-blue-600 text-white hover:bg-blue-700'
                  : 'bg-gray-300 text-gray-500 cursor-not-allowed'
                  }`}
              >
                {selectedDataset && selectedTask ? '开始分析' : '请先选择数据集和任务'}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}